<?php
// 引入七牛云SDK
require_once('qiniu/auth_digest.php');
require_once('qiniu/http.php');
require_once('qiniu/rs.php');

// 配置七牛云账号信息
$accessKey = ''; // 请填写您的AccessKey
$secretKey = ''; // 请填写您的SecretKey
Qiniu_SetKeys($accessKey, $secretKey);

$post = $_POST;
if(empty($post['act']))$post['act']='buckets';
if(empty($accessKey)){
    $resturn  = array('status'=>0,'msg'=>'请先配置AccessKey');ajaxReturn($resturn);
}
if(empty($secretKey)){
    $resturn  = array('status'=>0,'msg'=>'请先配置SecretKey');ajaxReturn($resturn);
}

// 创建标准HTTP客户端（用于获取buckets等不需要X-Qiniu-Date的请求）
$client = new Qiniu_MacHttpClient(null);
if($post['act']=='buckets'){
    // 七牛云API获取存储桶列表的URL
    $url = 'http://rs.qbox.me/buckets';
    // 调用API获取存储桶列表
    list($buckets, $err) = Qiniu_Client_Call($client, $url);
    if ($err !== null) {
        $resturn  = array('status'=>0,'msg'=>"获取存储桶列表失败: " . $err->Err);ajaxReturn($resturn);
    }
    $resturn=[];
    $resturn['status']=1;
    $resturn['msg']='获取成功';
    $resturn['count']=count($buckets);
    $resturn['list']=$buckets;
    ajaxReturn($resturn);
}
if($post['act']=='statics'){
    if(empty($post['bucket'])){
        $resturn  = array('status'=>0,'msg'=>'请选择bucket');ajaxReturn($resturn);
    }
    // 处理日期参数 - 用于常规接口（按天）
    $startDate = !empty($post['start'])?date('YmdHis',strtotime($post['start'])):gmdate('Ymd', strtotime('-1 day')) . '000000';
    $endDate = !empty($post['end'])?date('YmdHis',strtotime($post['end'])):gmdate('Ymd', strtotime('-1 day')) . '235959';
    
    // 处理月份参数 - 用于 blob_io 接口（按月）
    $monthParam = !empty($post['month']) ? $post['month'] : '';

    // 自定义HTTP客户端，添加X-Qiniu-Date请求头（用于统计数据API）
    class Stats_Qiniu_MacHttpClient extends Qiniu_MacHttpClient {
        public function RoundTrip($req) {
            // 添加X-Qiniu-Date请求头，格式为七牛云要求的格式：20060102T150405Z
            $req->Header['X-Qiniu-Date'] = gmdate('Ymd\THis\Z');
            
            // 调用父类方法
            return parent::RoundTrip($req);
        }
    }
    
    // 创建用于统计API的HTTP客户端
    $statsClient = new Stats_Qiniu_MacHttpClient(null);
    $data = getBucketStats($statsClient, $post['bucket'], $startDate, $endDate, $monthParam);
    
    $resturn=[];
    $resturn['status']=1;
    $resturn['msg']='获取成功';
    $resturn['list']=$data;
    ajaxReturn($resturn);
    
}
// 2. 获取存储桶的统计数据
function getBucketStats($statsClient, $bucket, $startDate = null, $endDate = null, $monthParam = null) {
    
    // 七牛云API获取存储桶统计数据的URL
    $url = 'http://api.qiniu.com/v6/space';
    $params = array(
        'bucket' => $bucket,
        'begin' => $startDate, // 只取年月日部分
        'end' => $endDate,     // 只取年月日部分
        'g' => 'day',
    );
    // 调用API获取存储桶空间统计数据
    list($spaceData, $err) = Qiniu_Client_CallWithForm($statsClient, $url, $params);
    
    if ($err !== null) {
        $space = "<div style='color:red' title='获取存储桶 $bucket 空间统计数据失败: " . $err->Err . "'>E</div>";
    }else{
        $storage = isset($spaceData['datas'][0]) ? $spaceData['datas'][0] : 0;
        $space = formatBytes($storage);
    }
    
    // 获取外网流出流量 - 按月调用
    $url = 'http://api.qiniu.com/v6/blob_io';
    
    // 处理月份参数，格式化为开始和结束日期
    $blobStartDate = '';
    $blobEndDate = '';
    
    if (!empty($monthParam)) {
        // 如果传入了月份参数，格式化为该月的第一天和最后一天
        $monthDate = date_create_from_format('Y-m', $monthParam);
        if ($monthDate) {
            $blobStartDate = $monthDate->format('Ymd') . '000000';
            $blobEndDate = $monthDate->format('Ymt') . '235959'; // t 表示月份中的总天数
        }
    }
    
    // 如果没有有效的月份参数，则默认使用最近一个月
    if (empty($blobStartDate)) {
        $blobStartDate = gmdate('Ymd', strtotime('-1 month')) . '000000';
        $blobEndDate = gmdate('Ymd') . '235959';
    }
    
    $paramsll = array(
        'begin' => $blobStartDate,
        'end' => $blobEndDate,
        'g' => 'month',
        '$bucket' => $bucket,
        'select' => 'flow',
        '$metric' => 'flow_out'
    );
    // 调用API获取存储桶流量统计数据
    list($fluxData, $err) = Qiniu_Client_CallWithForm($statsClient, $url, $paramsll);
    if ($err !== null) {
        $flux= "<div style='color:red' title='获取存储桶 $bucket 外网流出流量失败: " . $err->Err . "'>E</div>";
    }else{
        $outFlux = isset($fluxData[0]['values']['flow']) ? $fluxData[0]['values']['flow']  : 0;
        $flux= formatBytes($outFlux);
    }
    
    // 获取CDN 回源流量 - 按月调用
    $url = 'http://api.qiniu.com/v6/blob_io';
    $paramsll['select']='flow';
    $paramsll['$metric']='cdn_flow_out';
    // 调用API获取存储桶 CDN 回源流量
    list($cdn_flow_outData, $err) = Qiniu_Client_CallWithForm($statsClient, $url, $paramsll);
    if ($err !== null) {
        $cdn_flow_out =  "<div style='color:red' title='获取存储桶 $bucket  CDN 回源流量失败: " . $err->Err . "'>E</div>";
    }else{
        $cdnFlux = isset($cdn_flow_outData[0]['values']['flow']) ? $cdn_flow_outData[0]['values']['flow'] : 0;
        $cdn_flow_out=formatBytes($cdnFlux);
    }
    
    // 获取GET 请求次数 - 按月调用
    $url = 'http://api.qiniu.com/v6/blob_io';
    $paramsll['select']='hits';
    $paramsll['$metric']='hits';
    // 调用API获取存储桶 GET 请求次数
    list($hitsData, $err) = Qiniu_Client_CallWithForm($statsClient, $url, $paramsll);
    if ($err !== null) {
        $hits= "<div style='color:red' title='获取存储桶 $bucket  GET 请求次数失败: " . $err->Err . "'>E</div>";
    }else{
        $totalCount = isset($hitsData[0]['values']['hits']) ? $hitsData[0]['values']['hits'] : 0;
        $hits= number_format($totalCount);
    }
    
    // 获取标准存储的文件数量
    $url = 'http://api.qiniu.com/v6/count';
    
    // 调用API获取标准存储的文件数量
    list($countData, $err) = Qiniu_Client_CallWithForm($statsClient, $url, $params);
    
    if ($err !== null) {
        $count = "<div style='color:red' title='获取存储桶 $bucket 请求次数统计数据失败: " . $err->Err . "'>E</div>";
    }else{
        $totalCount = isset($countData['datas'][0]) ? $countData['datas'][0] : 0;
        $count = number_format($totalCount);
    }
    
    // 获取标准存储的文件数量
    $url = 'http://api.qiniu.com/v6/rs_put';
    // 使用原始参数（按天）
    $paramsPut = $params;
    $paramsPut['$bucket'] = $paramsPut['bucket'];
    $paramsPut['select'] = 'hits';
    unset($paramsPut['bucket']);
    
    // 调用API获取 PUT 请求次数
    list($putData, $err) = Qiniu_Client_CallWithForm($statsClient, $url, $paramsPut);
    
    if ($err !== null) {
        $put = "<div style='color:red' title='获取存储桶 $bucket  PUT 请求次数失败: " . $err->Err . "'>E</div>";
    }else{
        $putCount = isset($putData[0]['values']['hits']) ? $putData[0]['values']['hits'] : 0;
        $put = number_format($putCount);
    }
    
    $data= array(
        'space' => $space,
        'flux' => $flux,
        'count' => $count,
        'cdn_flow_out' => $cdn_flow_out,
        'hits' => $hits,
        'put' => $put
    );
    return $data;
}
/**
 * 将字节数转换为易读的文件大小格式
 * 
 * @param int $bytes 字节数
 * @param int $precision 保留的小数位数，默认为2
 * @return string 格式化后的文件大小
 */
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    
    // 计算大小
    $bytes /= pow(1024, $pow);
    // 或者使用位运算：$bytes /= (1 << (10 * $pow)); 
    
    return round($bytes, $precision) . ' ' . $units[$pow];
}
function ajaxReturn($array){
    $content=json_encode($array,JSON_UNESCAPED_UNICODE);
    if(empty($_GET['callback'])){
        echo $content;exit;
    }else{
        echo $_GET['callback']."(".$content.")";exit;
    }
}
?>